#include "WiFi.h"
#include "ArduinoJson.h"
#include "HTTPClient.h"

// JSON parsing
static DynamicJsonDocument doc(1024);
// HTTP request
HTTPClient http;

// Set WiFi name and password
const char* ssid = "ssid";
const char* password = "password";

// API service address
const char* apiServer = "https://api.map.baidu.com/weather/v1/?district_id=310115&data_type=all&ak=YourAK";

// Weather description
static String weathertext;
// Temperature
static int temp;
// Location name
static String name;
// Wind speed
static String wind_class;
// Relative humidity
static int rh;

// Retrieve weather information from the Baidu Maps API URL
void getWeather() {
  http.begin(apiServer);
  int httpCode = http.GET();
  delay(500);
  // If successful, print weather information
  if(httpCode == HTTP_CODE_OK){
    // Get response data
    String responseData = http.getString();
    // Parse JSON data
    deserializeJson(doc, responseData);
    // Get fields from the JSON object
    JsonObject result = doc["result"];
    JsonObject now = result["now"];
    JsonObject location = result["location"];

    // Get weather description
    weathertext = now["text"].as<String>();
    // Get temperature
    temp = now["temp"].as<int>();
    // Get wind speed
    wind_class = now["wind_class"].as<String>();
    // Get relative humidity
    rh = now["rh"].as<int>();
    // Get location name
    name = location["name"].as<String>();

    Serial.println("------------天气信息----------------");
    Serial.println(name);
    Serial.print("天气现象：");
    Serial.println(weathertext);
    Serial.print("温度：");
    Serial.println(temp);
    Serial.print("相对湿度：");
    Serial.println(rh);
    Serial.print("风力：");
    Serial.println(wind_class);
    Serial.println("-----------------------------------");
  }else{
    // Failed to retrieve data
    Serial.println("获取天气信息失败");
  }
  // Close the HTTP connection
  http.end();
}

void setup() {
  // Set baud rate to 115200
  Serial.begin(115200);

  // Connect to Wi-Fi
  Serial.println("Connecting to WiFi!");
  WiFi.begin(ssid, password);
  // Wait for Wi-Fi connection
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Wi-Fi 连接中。。。");
    delay(500);
  }
  Serial.println("Wi-Fi 连接成功！");
  Serial.println(WiFi.localIP());
}

void loop() {
  // Triggered when the Boot button is pressed
  if(digitalRead(0) == LOW){
    // If Wi-Fi connection is successful, retrieve weather information
    if(WiFi.status() == WL_CONNECTED){
      getWeather();
    }
    delay(200);
  }
  delay(200);
}